#include "ScreenUtils.h"
#include <QScreen>
#include <QGuiApplication>
#include <QPixmap>
#include <QColor>
#include <QDebug>
#include <QClipboard>

std::shared_ptr<ScreenUtils> ScreenUtils::m_spInstance;

void ScreenUtils::slot_capture()
{
//    if(m_qmlRoot)
//    {
//        //QObject::metaObject()->invokeMethod(m_qmlRoot, "hide", Qt::QueuedConnection);
//        QObject::metaObject()->invokeMethod(m_qmlRoot, "hideWindowAck", Qt::QueuedConnection);
//        //QObject::metaObject()->invokeMethod(m_qmlRoot, "show", Qt::QueuedConnection);
//    }

    auto screen = QGuiApplication::primaryScreen();
    auto pixmap = screen->grabWindow();
    m_image = pixmap.toImage();
    provider->image = m_image;
    emit image_update();
}

//QImage ScreenUtils::CaptureScreen()
//{
//    if(!m_qmlRoot) return QImage();

//    auto screen = QGuiApplication::primaryScreen();
//    auto pixmap = screen->grabWindow();
//    m_image = pixmap.toImage();
//    //QObject::metaObject()->invokeMethod(m_qmlRoot, "show", Qt::BlockingQueuedConnection);
//    m_image.save("test.png");

//    return m_image;
//}

void ScreenUtils::slot_done(const int x, const int y)
{
    QColor color = m_image.pixelColor(x, y);
    emit color_update(color);
//    if(m_qmlRoot)
//    {
//        QObject::metaObject()->invokeMethod(m_qmlRoot, "setColor", Q_ARG(QVariant, color));
//    }
}

void ScreenUtils::onSelectColor(const int x, const int y)
{
    QColor color = m_image.pixelColor(x, y);
    if(m_qmlRoot)
    {
        QObject::metaObject()->invokeMethod(m_qmlRoot, "setColor", Q_ARG(QVariant, color));
    }
}

//void ScreenUtils::Initialize(QObject *qmlRoot, QObject *parent)
//{
//    m_spInstance.reset(new ScreenUtils(qmlRoot, parent));
//}

//ScreenUtils* ScreenUtils::Instance()
//{
//    if(m_spInstance)
//    {
//        return m_spInstance.get();
//    }

//    return nullptr;
//}

ScreenUtils::ScreenUtils(QObject* parent)
    : QObject(parent)
    //, m_image()
    //, m_qmlRoot(qmlRoot)
{
    provider = new ScreenImageProvider;
//    if(qmlRoot)
//    {
//        QObject::connect(qmlRoot, SIGNAL(hideWindow()), this, SLOT(onHideWindow()));
//        QObject::connect(qmlRoot, SIGNAL(selectColor(int,int)), this, SLOT(onSelectColor(int,int)));
//    }
}

void ScreenUtils::slot_copy(QString val)
{
    QString color = val.mid(1);
    QClipboard *clip = QGuiApplication::clipboard();
    clip->setText(color);
    qDebug()<<"hex color is"<<color<<"\r\n";
}
void ScreenUtils::slot_copy(int r,int g,int b)
{
    QString color=QString("%1,%2,%3").arg(r).arg(g).arg(b);
    QClipboard *clip = QGuiApplication::clipboard();
    clip->setText(color);
    qDebug()<<"rgb color is"<<color<<"\r\n";
}
